package me.leiusual.sharing.ui.cart

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations.switchMap
import androidx.lifecycle.ViewModel
import me.leiusual.sharing.api.model.cartdetail.CartList
import me.leiusual.sharing.pref.Token
import me.leiusual.sharing.repository.CartRepository
import me.leiusual.sharing.repository.OrderRepository
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.util.extension.toLiveData
import javax.inject.Inject

/**
 * Create by leiusual on 2018/7/15
 */
class CartHomeViewModel @Inject constructor(
    private val cartRepository: CartRepository,
    private val orderRepository: OrderRepository,
    val token: Token
) : ViewModel() {

  // 列表

  private val _cartList = MutableLiveData<Boolean>()
  val cartListFirst: LiveData<Boolean> = _cartList
  val cartList: LiveData<Data<CartList>> = switchMap(_cartList) {
    cartRepository.cartList().toLiveData()
  }

  fun cartList(isFirst: Boolean) {
    _cartList.value = isFirst
  }

  // 变更

  private val _cartChange = MutableLiveData<ParamsCartChange>()
  val cartChange: LiveData<Data<Unit>> = switchMap(_cartChange) {
    cartRepository.cartChange(it.shopCartId, it.quantity).toLiveData()
  }

  fun cartChange(cartXId: Long, quantity: Int) {
    _cartChange.value = ParamsCartChange(cartXId, quantity)
  }

  data class ParamsCartChange(val shopCartId: Long, val quantity: Int)

  // 删除

  private val _cartRemove = MutableLiveData<Long>()
  val cartRemove: LiveData<Data<Unit>> = switchMap(_cartRemove) {
    cartRepository.cartRemove(it).toLiveData()
  }

  fun cartRemove(cartXId: Long) {
    _cartRemove.value = cartXId
  }

  // 检查

  private val _orderCheck = MutableLiveData<Map<Long, Int>>()
  val orderCheckParams: LiveData<Map<Long, Int>> = _orderCheck
  val orderCheck: LiveData<Data<Unit>> = switchMap(_orderCheck) {
    orderRepository.orderCheck(it).toLiveData()
  }

  fun orderCheck(map: Map<Long, Int>) {
    _orderCheck.value = map
  }
}